package cn.cocho.android.mc.comp.edit;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import cn.cocho.android.mc.character.StringUtils;

public class EditTextAttach extends EditText {

	private Drawable[] drawable;
	private int drawableTouchRect = 0;// 清除图标的触摸区域
	private int touchLimit = 0;// 进入清除图标触摸区域的界限
	private int interval = 10;// 清除图标距离编辑框右侧的间隔
	private OnDrawableListener drawableListener = null;

	public EditTextAttach(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	/**
	 * 获取右侧drawable图标信息
	 * 
	 * @author yzl
	 * @time 2013-5-15下午5:18:26
	 */
	private void init() {
		drawable = this.getCompoundDrawables();
		if (drawable[2] != null) {
			drawableTouchRect = drawable[2].getIntrinsicWidth() + interval;
			addTextChangedListener(new BaseTextWatcher());
			if (StringUtils.isEmpty(getText().toString())) {
				setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
			} else {
				setCompoundDrawablesWithIntrinsicBounds(null, null, drawable[2], null);
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		if (touchLimit == 0) {
			touchLimit = getWidth() - drawableTouchRect;
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:
			if (drawableTouchRect == 0) {
				return true;
			}
			int curX = (int) event.getX();
			if (curX > touchLimit && !TextUtils.isEmpty(getText())) {
				performDrawableListener();
				return true;// consume touch even
			}
			break;
		}
		return true;
	}

	private void performDrawableListener() {
		if (drawableListener == null)
			return;
		drawableListener.onClick();
	}

	public OnDrawableListener getTouchListener() {
		return drawableListener;
	}

	public void setOnDrawableListener(OnDrawableListener drawableListener) {
		this.drawableListener = drawableListener;
	}
	
	/**
	 * 自定义接口实现点击drawable触发的事件
	 * 
	 * @author yzl
	 * @time 2013-5-16下午2:28:44
	 */
	public interface OnDrawableListener {
		public void onClick();
	}
	
	public void setDrawableState(Editable s){
		if (TextUtils.isEmpty(s)) {
			setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
		} else {
			setCompoundDrawablesWithIntrinsicBounds(null, null, drawable[2], null);
		}
	}
	
	/**
	 * 监听EditText的输入
	 * 
	 * @author yzl
	 * @time 2013-5-15下午5:16:00
	 */
	class BaseTextWatcher implements TextWatcher {
		@Override
		public void afterTextChanged(Editable s) {
			setDrawableState(s);
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

	}
}
